﻿using client.render;
using client.utils;
using CommunicationProtocol.dto;
using CommunicationProtocol.dto.command.client;
using CommunicationProtocol.dto.command.server;
using server.filter;
using server.filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CommunicationProtocol.dto.game;

namespace client.filter
{
    public class ServerCommandParser : NetFilter
    {
        private Form form;

        DynamicObjectCreator dynamicObjectCreator;

        BuyablePlantCreator buyablePlantCreator;

        public ServerCommandParser(Form form)
        {
            this.form = form;
            dynamicObjectCreator = new DynamicObjectCreator(form, 350, 177);
            buyablePlantCreator = new BuyablePlantCreator(form, 300, 50);
            
        }

        public void invoke(object buffer, InvocationChain invocationChain)
        {
            if (!(buffer is byte[])) {
                throw new ArgumentException();
            }

            byte[] data = (byte[])buffer;

            int functionType = data[0];

           

            byte[] remainingData = new ArraySegment<byte>(data, 1, data.Length - 1).ToArray();

            switch (functionType)
            {

                case 101:
                    {
                        // 创建用于攻击的植物
                        CreatingPlantCommand serverCommand = new CreatingPlantCommand(remainingData);

                        foreach (DynamicPlant baseObject in serverCommand)
                        {
                            dynamicObjectCreator.Execute(baseObject);
                        }
                        


                        break;
                    };
                case 102:
                    {
                        // 创建可选择的植物列表
                        RenderBuyablePlantListCommand serverCommand = new RenderBuyablePlantListCommand(remainingData);


                        foreach (var plant in serverCommand.plants) {
                            buyablePlantCreator.Execute(plant);
                        }

                        
                        break;
                    };
                case 103:
                    {
                        PlantBuyableStatusResp command = new PlantBuyableStatusResp(remainingData);

                        new FollowingMousePicture(form).copyPlantTemplate(command);

                        break;
                    };
                case 104: {
                        // 被要求登录
                        new InvocationChain(OutBandHolder.OutBand)
                            .invoke(new LoginRequest("玩家ID "+new Random().Next(100)));
                        break;
                    }


                default:
                    {
                        throw new ArgumentException("不支持的功能类型" + functionType);

                    }
            }
          
        }
    }
}
